<template>
  <main>
    <div>
      <p v-show="pending">Pending...</p>
      <p>Edit :{{ data }}</p>

      <form @submit.prevent="" @change="onFileChange" class="my-3">
        <v-text-field v-model="data.name" type="text" />

        <v-select v-model="data.status" :items="['PENDING', 'READY', 'DELETED', 'ERROR']">
        </v-select>

        <v-btn @click="cancel" class="ma-5">Annuler</v-btn>
        <v-btn @click="save" class="ma-5">Enregistrer</v-btn>
        <v-btn @click="deleteAndGoBack" class="ma-5">Supprimer</v-btn>
        <v-btn @click="refresh" class="ma-5">Refresh</v-btn>
      </form>
    </div>
  </main>
</template>

<script setup lang="ts">
import {useEntityManager} from "~/composables/data/useEntityManager";
import {ref, Ref} from "@vue/reactivity";
import ApiResource from "~/models/ApiResource";
import {File} from "~/models/Core/File";
import {navigateTo, useAsyncData} from "#app";

const route = useRoute()

const id: Ref<number> = ref(parseInt(route.params.id as string))
const valid: Ref<boolean> = ref(true)

const em = useEntityManager()

const { data, pending, refresh } =  useAsyncData(
    'file_' + id.value,
    () => em.fetch(File, id.value)
)
//@ts-ignore
const file = reactive(data.value) as ApiResource

const onFileChange = () => {
  console.log(file)
  em.getRepository(File).save(file)
}


const save = async () => {
  await em.persist(File, file)
}

const cancel = async () => {
  if (em.isNewEntity(File, id.value)) {
    await em.delete(File, file)
  } else {
    em.reset(File, file)
  }
}

const deleteItem = async () => {
  await em.delete(File, file)
}

const goBack = () => {
  navigateTo('/poc')
}

const saveAndGoBack = async () => {
  await save()
  goBack()
}

const cancelAndGoBack = async () => {
  await cancel()
  goBack()
}

const deleteAndGoBack = async () => {
  await deleteItem()
  goBack()
}
</script>

<style>
</style>
